import React, { PureComponent } from 'react'
import { Button, Form, Input, InputNumber, Select, Icon, Alert, notification } from 'antd'
import Modal from 'kenote-react-admin-modal'
import QueueAnim from 'rc-queue-anim'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { adminsUserActions, passportActions } from '../reduxs'
import { HttpServices, REDUX_FETCH_TIMEOUT, validRule, getTeamFlag } from 'services/utils'
import { getToken, setToken } from 'services/token'
import _ from 'lodash'
import 'styles/modal.scss'

const FormItem = Form.Item
const TextArea = Input.TextArea
const Option = Select.Option

@connect(
  state => ({
    editPending     : state.AdminsUser.editPending,
    editError       : state.AdminsUser.editError,
    editMessage     : state.AdminsUser.editMessage,
    listData        : state.AdminsUser.listData,
    groupList       : state.AdminsGroup.listData,
    auth            : state.Passport.auth,
    rules           : state.Passport.rules
  }),
  dispatch => ({
    actions: bindActionCreators({ ...adminsUserActions, updateAuth: passportActions.updateAuth }, dispatch)
  })
)
@Form.create()
export default class EditAdminsUserModal extends PureComponent {

  constructor (props) {
    super(props)
    const { ModalOpts, listData } = props
    const userInfo = getUserInfo(listData, ModalOpts.id)
    this.state = {
      disabled: true,
      alert: null,
      password_eye: false,
      fieldByUserName: userInfo.username,
      fieldByGroup: userInfo.group,
      fieldByEmail: userInfo.email,
      fieldByNickName: userInfo.nickname,
      //fieldByDesc: userInfo.desc
    }
    this._Modal = null
    this._Form = null
  }
  
  componentWillReceiveProps (nextProps) {
    const { editError, editMessage,  } = nextProps
    if (editError > 0 && editMessage !== this.props.editMessage) {
      this.setState({ alert: (
        <Alert
          style={{ margin: '0 40px 24px' }}
          message={editMessage}
          type="error"
          showIcon
          key="aaa"
        />
      )})
    }
    if (editError === 0 && editMessage !== this.props.editMessage) {
      this._Modal.handleOnCancel()
      notification.info({
        message: `系统提示`,
        description: `用户组信息更新成功！`,
        duration: 8,
        placement: 'bottomRight'
      })
      if (this.props.auth._id === this.props.ModalOpts.id) {
        let userInfo = getUserInfo(this.props.listData, this.props.ModalOpts.id)
        this.props.actions.updateAuth(userInfo)
      }
    }
  }
  
  render () {
    const { visible, onCancel, form, editPending, auth, groupList, rules } = this.props
    const { getFieldDecorator } = form
    const { group } = auth
    const options = {
      ref: view => this._Modal = view,
      visible: visible,
      onCancel: onCancel,
      title: '编辑用户信息',
      footer: [
        <Button
          onClick={() => this._Modal.handleOnCancel()}
          >
          取消
        </Button>,
        <Button
          type="primary"
          loading={editPending}
          onClick={this.handleSubmit}
          >
          确定
        </Button>
      ],
      width: 600,
      maskClosable: false
    }
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    }
    return (
      <Modal {...options}>
        <br />
        <Form 
          ref={ view => this._Form = view }
          layout="horizontal" 
          onSubmit={this.handleSubmit}
          >
          {editPending ? null : (
            <QueueAnim component="div" type={['bottom', 'top']} leaveReverse>
              {this.state.alert ? this.state.alert : null}
            </QueueAnim>
          )}
          <FormItem 
            {...formItemLayout} 
            label="用户名" 
            >
            {getFieldDecorator('username', {
              rules: [
                { required: true, message: '用户名不能为空!' },
                { validator: this.checkUsername.bind(this, rules['username']) },
                { validator: this.checkFindUsername.bind(this, rules['username']) }
              ],
              initialValue: this.state.fieldByUserName
            })(
              <Input disabled={group.level < 9999} />
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="用户组" 
            >
            {getFieldDecorator('group', {
              initialValue: this.state.fieldByGroup['_id']
            })(
              <Select 
                size="Small"
                disabled={this.state.fieldByGroup['level'] === 9999 || group.level <= this.state.fieldByGroup['level']}
                >
                {groupList && _.filter(groupList, o => o.level < (this.state.fieldByGroup['level'] !== 9999 ? 9999 : 9999 + 1)
                  && (auth.group.level !== 9999 ? getTeamFlag(o.team, auth) : true)).map((item, i) => {
                  return (
                    <Option key={i} value={item._id} disabled={group.level <= item.level}>{item.name}</Option>
                  )
                })}
              </Select>
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="登录密码" 
            >
            {getFieldDecorator('password', {
              rules: [
                { validator: this.checkNewPassword.bind(this, rules['password']) }
              ],
            })(
              <div>
                <Input 
                  type={this.state.password_eye ? 'text' : 'password'} 
                  style={{ width: 220 }} 
                  suffix={(
                    <Icon 
                      type={this.state.password_eye ? 'eye' : 'eye-o'} 
                      onClick={this.handleLookPassword}
                      style={{ fontSize: 16, color: '#bfbfbf' }}
                      />
                  )} 
                  />
                <Icon type="exclamation-circle" style={{ marginLeft: 10 }} />
                <span style={{ marginLeft: 4, color: '#999999' }}>不修改密码可不填</span>
              </div>
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="E-mail" 
            >
            {getFieldDecorator('email', {
              rules: [
                { required: true, message: 'E-mail不能为空!' },
                { validator: this.checkEmail.bind(this, rules['email']), message: 'E-mail格式错误' },
                { validator: this.checkFindEmail.bind(this, rules['email']) }
              ],
              initialValue: this.state.fieldByEmail
            })(
              <Input />
            )}
          </FormItem>
          <FormItem 
            {...formItemLayout} 
            label="昵称" 
            >
            {getFieldDecorator('nickname', {
              rules: [
                { validator: this.checkNickname.bind(this, rules['nickname']), message: '昵称格式错误' }
              ],
              initialValue: this.state.fieldByNickName
            })(
              <Input style={{ width: 250 }} />
            )}

            <Button 
              type="dashed"
              style={{ marginLeft: 10 }}
              disabled={_.isEmpty(_.trim(form.getFieldsValue()['username']))}
              onClick={this.handleCopyUsername}
              >
              从用户名复制
            </Button>
          </FormItem>
        </Form>
      </Modal>
    )
  }
  
  handleSubmit = (e) => {
    e && e.preventDefault()
    const { ModalOpts } = this.props
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (this.state.fieldByGroup['level'] === 9999 || group.level <= this.state.fieldByGroup['level']) {
          _.unset(values, 'group')
        }
        for (let key of _.keys(values)) {
          !values[key] && _.unset(values, key)
        }
        this.props.actions.edit(ModalOpts.id, values)
      }
    })
  }

  handleLookPassword = () => {
    this.setState({ password_eye: !this.state.password_eye })
  }

  handleCopyUsername = () => {
    let { username } = this.props.form.getFieldsValue()
    this.props.form.setFieldsValue({ nickname: username })
  }

  checkUsername (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (value && !validByValue.valid) {
      callback(rule.message || validByValue.message || '用户名格式错误')
    }
    callback()
  }

  async checkFindUsername (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (validByValue.valid) {
      let header = { Authorization: getToken() }
      let result = await HttpServices.GET(`/admins/user/username`, { v: _.trim(value), exc: this.state.fieldByUserName }, header)
      if (result.Status.code > 0) {
        callback(result.Status.message)
      }
    }
    callback()
  }

  checkNewPassword (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (value && !validByValue.valid) {
      callback(rule.message || validByValue.message || '密码格式错误')
    }
    callback()
  }

  checkEmail (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (value && !validByValue.valid) {
      callback(rule.message || validByValue.message || 'E-Mail格式错误')
    }
    callback()
  }

  async checkFindEmail (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (validByValue.valid) {
      let header = { Authorization: getToken() }
      let result = await HttpServices.GET(`/admins/user/email`, { v: _.trim(value), exc: this.state.fieldByEmail }, header)
      if (result.Status.code > 0) {
        callback(result.Status.message)
      }
    }
    callback()
  }

  checkNickname (Rule, rule, value, callback) {
    let validByValue = validRule(Rule, value)
    if (value && !validByValue.valid) {
      callback(rule.message || validByValue.message || '昵称格式错误')
    }
    callback()
  }
}

function getUserInfo (listData, id) {
  return _.find(listData, { _id: id })
}